<script setup lang="ts">
import { onMounted, ref } from 'vue';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import { useEcharts } from '@/hooks/common/echarts';
import { getMoldDataStatisticsByYear } from '@/service/api/modules/workwear/mold-data-statistics';

defineOptions({
  name: 'LineChart'
});
const loading = ref(false);
const keys = [
  'midnightToFourAm',
  'fourAmToEightAm',
  'eightAmToNoon',
  'noonToFourPm',
  'fourPmToEightPm',
  'eightPmToMidnight'
];

const dateFormat = 'YYYY';

const year = ref<Dayjs>(dayjs(dayjs().format(dateFormat), dateFormat));

function generateRandomArray(length) {
  const randomArray = [];
  for (let i = 0; i < length; i++) {
    const randomNumber = Math.floor(Math.random() * 100) + 1; // 生成1-100之间的随机整数
    randomArray.push(randomNumber);
  }
  return randomArray;
}

const { domRef, updateOptions } = useEcharts(
  () => ({
    toolbox: {
      show: true,
      feature: {
        magicType: { type: ['line', 'bar'] },
        saveAsImage: {}
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      },
      formatter(params) {
        let str = `${year.value.format(dateFormat)}-${params[0].name}月<br />`;

        if (params[0]) {
          str += ` ${params[0]?.marker}使用数量：${params[0].value}`;
        }
        if (params[1]) {
          str += `<br />${params[1]?.marker}新增数量：${params[1].value}`;
        }
        if (params[2]) {
          str += `<br />${params[2]?.marker}报废数量：${params[2].value}`;
        }

        return str;
        // return `${year.value.format(dateFormat)}-${params[0].name}月<br />${params[0].marker}报废数量：${params[0].value}<br />${params[1].marker}新增数量：${params[1].value}<br />${params[2].marker}冲数：${params[2].value}`;
      }
    },
    legend: {
      data: ['使用数量', '新增数量', '报废数量'],
      top: 25
    },
    title: {
      text: `${year.value.format(dateFormat)}年统计`,
      left: 'center',
      top: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        color: '#90EE90',
        name: '使用数量',
        type: 'line',
        smooth: true,
        stack: 'Total',
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0.25,
                color: '#90EE90'
              },
              {
                offset: 1,
                color: '#fff'
              }
            ]
          }
        },
        emphasis: {
          focus: 'series'
        },
        data: []
      },

      {
        color: '#26deca',
        name: '新增数量',
        type: 'line',
        smooth: true,
        stack: 'Total',
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0.25,
                color: '#26deca'
              },
              {
                offset: 1,
                color: '#fff'
              }
            ]
          }
        },
        emphasis: {
          focus: 'series'
        },
        data: []
      },
      {
        color: '#8e9dff',
        name: '报废数量',
        type: 'line',
        smooth: true,
        stack: 'Total',
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0.25,
                color: '#8e9dff'
              },
              {
                offset: 1,
                color: '#fff'
              }
            ]
          }
        },
        emphasis: {
          focus: 'series'
        },
        data: []
      }
    ]
  }),
  false
);

function getData() {
  loading.value = true;
  getMoldDataStatisticsByYear({
    year: year.value.format('YYYY')
  })
    .then(({ data, error }) => {
      console.log('年统计数据', data);

      if (!error) {
        updateOptions(opts => {
          // 新增数量
          const newData = data?.new?.map(item => item.punchTotal || 0);
          // 使用数量
          const usedData = data?.useData?.map(item => item.punchNum || 0);
          // 报废数量
          const scrapData = data?.useless?.map(item => item.punchTotal || 0);
          opts.series[0].data = usedData;
          opts.series[1].data = newData;
          opts.series[2].data = scrapData;
          return opts;
        });
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleYearChange(value: Dayjs) {
  console.log('value', value);
  getData();
  updateOptions(opts => {
    opts.title.text = `${value.format(dateFormat)}年报废新增冲数统计`;
    return opts;
  });
}

onMounted(() => {
  getData();
});
</script>

<template>
  <ACard :bordered="false" class="card-wrapper">
    <ASpin tip="数据加载中..." :spinning="loading">
      <div ref="domRef" class="h-full overflow-hidden"></div>
      <div class="select-year">
        <ADatePicker
          v-model:value="year"
          :allow-clear="false"
          picker="year"
          size="small"
          format="YYYY"
          @change="handleYearChange"
        />
      </div>
    </ASpin>
  </ACard>
</template>

<style scoped>
.select-year {
  position: absolute;
  top: 0px;
  left: 10px;
}
</style>
